from tqdm import tqdm
import argparse
"""
    将四位二进制字符串转换为一位十六进制字符串。
    Args:
        binary_str (str): 四位二进制字符串。
        
    Returns:
        str: 对应的一位十六进制字符串。
"""
def binary_to_hex(binary_str):
    try:
        # 确保只处理四位长度的二进制字符串
        if len(binary_str) != 4 or not all(c in '01' for c in binary_str):
            raise ValueError("Input must be a four-bit binary string.")
        
        # 转换为十六进制
        return f"{int(binary_str, 2):X}"
    except ValueError as e:
        print(f"Error: {e}")
        return None

"""
    将十六进制字符串写入文件，每个地址存储两位十六进制，大写。
    Args:
        hex_str (str): 十六进制字符串。
        file_path (str): 要写入的文件路径。
"""
def write_hex_to_file(hex_str, file_path):
    with open(file_path, 'wb') as file:
        # 将十六进制字符串转换为字节
        bytes_to_write = bytes.fromhex(hex_str)
        file.write(bytes_to_write)

def main():
    parser = argparse.ArgumentParser(description="Convert .bit file to .rbt")
    parser.add_argument('rbt_file_path', type=str, help="input .rbt file path")
    parser.add_argument('bit_file_path', type=str, help="output .bit file path")
    
    args = parser.parse_args()
    
    hex_str = []

    with open(args.rbt_file_path,"r") as f:
        lines = f.readlines()
        with tqdm(total=len(lines), desc="Processing Lines") as pbar:
            for line in lines:
                binary_data = line.strip()
                cur_len = len(binary_data)
                try:
                    if cur_len%4 != 0: 
                        raise ValueError("Input must be a four-bit binary string.")
                    for i in range(0, cur_len, 4):
                        hex_str.append(binary_to_hex(binary_data[i:i+4]))
                except ValueError as e:
                    print(f"Error: {e}")
                except Exception as e:
                    print(f"Unexpected error: {e}")
                pbar.update(1)  # Update the progress bar after processing each line
    hex_str = "".join(hex_str)
    write_hex_to_file(hex_str, args.bit_file_path)

if __name__ == "__main__":
    main()


